package com.skyworth.ui.customview;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.LinearLayout;

/**
 * Created by luwei on 15-11-13.
 * 简单的listview 不支持view回收，有多少数据就会有多少个view,不支持滚动
 */
public class SimpleListView extends LinearLayout implements BaseAdapter.ObserverListener,
        View.OnFocusChangeListener,View.OnKeyListener,ISimpleListView{
    private Context context = null;
    private BaseAdapter adapter = null;
    private int divide = 0;
    private int divideResource = 0;
    private FILL_MODE fillMode = FILL_MODE.FILL_PARENT;
    private OnItemFocusChangeListener itemFocusChangeListener = null;
    private int current = 0;
    private OnClickListener clickListener = null;
    private boolean shieldLeft = false;
    private boolean shieldRight = false;
    private boolean shieldUp = false;
    private boolean shieldDown = false;
    private boolean shieldAll = false;
    private boolean alwaysFocus = false;
    private int alwaysFocusPos = 0;
    private OnKeyListener focusKeyListener = null;
    private OnBoundaryListener boundaryListener = null;

    @Override
    public void shieldKey(boolean left, boolean up, boolean right, boolean down) {
        this.shieldLeft = left;
        this.shieldUp = up;
        this.shieldRight = right;
        this.shieldDown = down;
    }

    private boolean forbidOutBound = true;
    private View lastView = null;



    public void setClickListener(OnClickListener listener){
        this.clickListener = listener;
    }

    public void setFocusKeyListener(OnKeyListener keyListener){
        this.focusKeyListener = keyListener;
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        Log.i("shield","shield all " + shieldAll);
        if (shieldAll)
            return true;
        if (event.getAction() == KeyEvent.ACTION_DOWN){
            if (forbidOutBound){
                switch (keyCode){
                    case KeyEvent.KEYCODE_DPAD_DOWN:
                        if (getOrientation() == VERTICAL){
                            if (v.equals(getChildAt(getChildCount() -1)))
                                if (boundaryListener != null)
                                    return boundaryListener.onDownBoundary(v);
                            if (shieldDown && v.equals(getChildAt(getChildCount() -1)))
                                return true;
                        }else{
                            if (boundaryListener != null)
                                return boundaryListener.onDownBoundary(v);
                            if (shieldDown)
                                return true;
                        }
                        break;
                    case KeyEvent.KEYCODE_DPAD_RIGHT:
                        if (getOrientation() == VERTICAL){
                            if (boundaryListener != null)
                                return boundaryListener.onRightBoundary(v);
                            if (shieldRight)
                                return true;
                        }else{
                            if (v.equals(getChildAt(getChildCount() -1)))
                                if (boundaryListener != null)
                                    return boundaryListener.onRightBoundary(v);
                            if (shieldRight && v.equals(getChildAt(getChildCount() -1)))
                                return true;
                        }
                        break;
                    case KeyEvent.KEYCODE_DPAD_UP:
                        if (getOrientation() == VERTICAL){
                            if (v.equals(getChildAt(0)))
                                if (boundaryListener != null)
                                    return boundaryListener.onTopBoundary(v);
                            if (shieldUp && v.equals(getChildAt(0)))
                                return true;
                        }else{
                            if (boundaryListener != null)
                                return boundaryListener.onTopBoundary(v);
                            if (shieldUp)
                                return true;
                        }
                        break;
                    case KeyEvent.KEYCODE_DPAD_LEFT:
                        if (getOrientation() == VERTICAL){
                            if (boundaryListener != null)
                                return boundaryListener.onLeftBoundary(v);
                            if (shieldLeft)
                                return true;
                        }else{
                            if (v.equals(getChildAt(0)))
                                if (boundaryListener != null)
                                    return boundaryListener.onLeftBoundary(v);
                            if (shieldLeft && v.equals(getChildAt(0)))
                                return true;
                        }

                        break;
                }
                if (focusKeyListener != null)
                    focusKeyListener.onKey(v,keyCode,event);
            }
        }
        return false;
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus){
            if (v.equals(this)){
                if (getChildCount() == 0)
                    return;
                enableChildFocus(true);
                if (alwaysFocus) {
                    if (getChildAt(alwaysFocusPos) != null)
                        getChildAt(alwaysFocusPos).requestFocus();
                }else {
                    Log.i("category","current " + current);
                    if (getChildAt(current) != null) {
                        Log.i("category","category focus " + current);
                        getChildAt(current).requestFocus();
                    }
                }
                enableFocus(false);
                if (itemFocusChangeListener != null)
                    itemFocusChangeListener.onFocus();
            }else {
                current = v.getId();
                v.setSelected(true);
                if (itemFocusChangeListener != null)
                    itemFocusChangeListener.onFocusItem(v.getId(), v, hasFocus);
            }
        }else {
            v.setSelected(false);
            if (getChildCount() != 0 && !isChildFocus()) {
                if (itemFocusChangeListener != null && !v.equals(this))
                    itemFocusChangeListener.onNothingFocus(v);
                enableChildFocus(false);
                enableFocus(true);
            }
        }
    }


    public void setOnItemFocusChangeListener(OnItemFocusChangeListener listener){
        this.itemFocusChangeListener = listener;
    }

    public enum FILL_MODE{
        FILL_PARENT,
        SCROLL
    }

    public SimpleListView(Context context) {
        super(context);
        init(context);
    }

    public SimpleListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SimpleListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context){
        this.context = context;
        enableFocus(true);
        setOnFocusChangeListener(this);
    }

    public void enableFocus(boolean focus){
        setFocusable(focus);
        setFocusableInTouchMode(focus);
    }

    /**
     * 设置每个child的间距
     * @param divide
     */
    public void setDivide(int divide){
        this.divide = divide;
    }

    /**
     * 设置每个child的间距图片，暂时无用
     * @param id
     */
    public void setDivideImageResource(int id){
        this.divideResource = id;
    }

    protected void setFillMode(FILL_MODE mode){
        this.fillMode = mode;
    }


    /**
     * 设置adapter
     * @param adapter
     */
    public void setAdapter(BaseAdapter adapter){
        this.adapter = adapter;
        adapter.registObserver(this);
        adapter.notifyDataSetChanaged();
    }

    /**
     * 设置child显示时的动画
     * @param id 动画id
     */
    public void setAnimation(int id) {
        AnimationSet set = (AnimationSet)AnimationUtils.loadAnimation(context, id);
        LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);
        controller.setOrder(LayoutAnimationController.ORDER_NORMAL);
        setLayoutAnimation(controller);
    }

    @Override
    public void onChanaged() {
        final int count = adapter.getCount();
        current = 0;
        removeAllViews();
        adapter.destroy();
        for (int i = 0; i < count; i++){
            View view = adapter.getView(i, null,this);
            view.setId(i);
            view.setOnClickListener(clickListener);
            view.setOnKeyListener(this);
            LayoutParams params = (LayoutParams)view.getLayoutParams();
            if (i != 0){
                int marginLeft = 0;
                int marginTop = 0;
                if (getOrientation() == LinearLayout.HORIZONTAL) {
                    marginLeft = divide;
                }else {
                    marginTop = divide;
                }
                params.topMargin = marginTop;
                params.leftMargin = marginLeft;
            }
            addView(view);
        }
        enableChildFocus(false);
    }

    public int getSelectedPos(){
        int count = getChildCount();
        for (int i = 0; i < count; i++){
            if (getChildAt(i).isSelected())
                return i;
        }
        return -1;
    }

    public int getFocusPos(){
        int count = getChildCount();
        for (int i = 0; i < count; i++){
            if (getChildAt(i).isFocused())
                return i;
        }
        return -1;
    }


    private boolean isChildFocus(){
        int count = getChildCount();
        for (int i = 0; i < count; i++){
            if (getChildAt(i).isFocused())
                return true;
        }
        return false;
    }

    @Override
    public OnFocusChangeListener getOnFocusChangeListener() {
        return this;
    }

    private void enableChildFocus(boolean focus){
        int count = getChildCount();
        for (int i = 0; i < count; i++){
            getChildAt(i).setFocusable(focus);
            getChildAt(i).setFocusableInTouchMode(focus);
            getChildAt(i).setEnabled(focus);
        }
    }

    /**
     * 手动设置child获取焦点
     * @param pos 位置
     */
    public void setFocus(int pos){
        enableChildFocus(true);
        if (pos < getChildCount()) {
            if (!isChildFocus()){
                if (itemFocusChangeListener != null)
                    itemFocusChangeListener.onFocus();
            }
            getChildAt(pos).requestFocus();
        }
    }

    /**
     * 手动改变child的select状态
     * @param pos 位置
     * @param selected 是否select
     */
    public void setSelected(int pos,boolean selected){
        if (pos < getChildCount()) {
            getChildAt(pos).setSelected(selected);
            if (selected)
                current = pos;
        }
    }

    public void setBoundaryListener(OnBoundaryListener listener){
        this.boundaryListener = listener;
    }


    /**
     * 获取adapter
     * @return
     */
    public BaseAdapter getAdapter(){
        return adapter;
    }

    @Override
    public void setTranslationX(float translationX) {
        super.setTranslationX(translationX);
    }

    public void shieldAllKey(boolean key){
        this.shieldAll = key;
    }

    public void setAlwaysFocusPos(int pos){
        this.alwaysFocusPos = pos;
        this.alwaysFocus = true;
    }
}
